<template>
  <div class="search">
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    ></van-nav-bar>

    <!-- 搜索框 -->
    <van-search
      v-model.trim="value"
      show-action
      shape="round"
      placeholder="请输入搜索关键词"
      @input="onInput"
      @search="onSearch(value)"
    >
      <template #action>
        <div @click="onSearch(value)">搜索</div>
      </template>
    </van-search>
    <van-cell-group v-if="value">
      <van-cell
        @click="onSearch(item)"
        icon="search"
        v-for="(item, index) in sugList"
        :key="index"
      >
        <span v-html="highLight(item)"></span>
      </van-cell>
    </van-cell-group>
    <!-- 历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"></van-cell>
      <van-cell
        @click="result(item)"
        v-for="(item, index) in history"
        :key="index"
        :title="item"
      >
        <van-icon name="close" @click.stop="delHistroy(item)" />
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { setSearchHistory, getSearchHistory } from '@/utils/storage'
import { getSuggest } from '@/api/search'
export default {
  name: 'Search',
  data() {
    return {
      value: '',
      sugList: [],
      history: getSearchHistory()
    }
  },
  methods: {
    onInput() {
      clearTimeout(this.timeId)
      this.timeId = setTimeout(async () => {
        if (!this.value) return
        const res = await getSuggest(this.value)
        if (!res.data.options[0]) return
        this.sugList = res.data.options
      }, 300)
    },
    onSearch(val) {
      this.value = val
      this.history = this.history.filter((item) => item !== val)
      this.history.unshift(this.value)
      setSearchHistory(this.history)
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: val
        }
      })
    },
    delHistroy(val) {
      this.history = this.history.filter((item) => item !== val)
      setSearchHistory(this.history)
    },
    result(item) {
      this.$router.push({
        path: '/search/result',
        query: {
          keyword: item
        }
      })
    },
    highLight(str) {
      if (!str) return
      return str.replace(
        new RegExp(this.value, 'gi'),
        (math) => `<span style="color: red;">${math}</span>`
      )
    }
  }
}
</script>

<style lang="less" scoped>
.shuju {
  text-align: center;
}
</style>
